import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { login as loginApi, getUserInfo as getUserInfoApi, getUserMenus, logout as logoutApi, getUserPermissions } from './api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: Cookies.get('token') || '',
    userInfo: null,
    permissions: [],
    roles: [],
    menus: []
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 用户名
    username: (state) => state.userInfo?.username || '',
    
    // 用户头像
    avatar: (state) => state.userInfo?.avatar || '',
    
    // 用户昵称
    nickname: (state) => state.userInfo?.nickname || state.userInfo?.username || '',
    
    // 是否有指定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },
    
    // 是否有指定角色
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    }
  },

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      Cookies.set('token', token, { expires: 7 }) // 7天过期
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 设置权限
    setPermissions(permissions) {
      this.permissions = permissions
    },

    // 设置角色
    setRoles(roles) {
      this.roles = roles
    },

    // 设置菜单
    setMenus(menus) {
      this.menus = menus
    },

    // 登录
    async login(loginForm) {
      try {
        const response = await loginApi(loginForm)

        this.setToken(response.data.token)
        this.setUserInfo(response.data.user)

        // 登录成功后立即获取菜单和权限
        try {
          const [menusResponse, permissionsResponse] = await Promise.all([
            getUserMenus(),
            getUserPermissions()
          ])

          this.setMenus(menusResponse.data || [])
          this.setPermissions(permissionsResponse.data || [])
        } catch (menuError) {
          console.error('获取菜单和权限失败:', menuError)
          // 即使菜单权限获取失败，也不影响登录流程
        }

        return response.data
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo(forceRefresh = false) {
      try {
        // 如果已有用户信息且不强制刷新，直接返回
        if (this.userInfo && !forceRefresh) {
          return this.userInfo
        }

        const response = await getUserInfoApi()
        this.setUserInfo(response.data)

        // 如果还没有菜单和权限信息，则获取
        if (!this.menus.length || !this.permissions.length) {
          try {
            const [menusResponse, permissionsResponse] = await Promise.all([
              getUserMenus(),
              getUserPermissions()
            ])

            this.setMenus(menusResponse.data || [])
            this.setPermissions(permissionsResponse.data || [])
          } catch (menuError) {
            console.error('获取菜单和权限失败:', menuError)
            // 即使菜单权限获取失败，也不影响用户信息获取
          }
        }

        return response.data
      } catch (error) {
        throw error
      }
    },

    // 登出
    async logout() {
      try {
        // 先调用后端登出接口
        await logoutApi()

        // 接口调用成功后清除本地数据
        this.clearUserData()
      } catch (error) {
        console.error('登出接口调用失败:', error)

        // 如果是401错误（token已失效）或网络错误，也清除本地数据
        if (error.response?.status === 401 || !error.response) {
          this.clearUserData()
        } else {
          // 其他错误，抛出异常让调用方处理
          throw error
        }
      }
    },

    // 清除用户数据
    clearUserData() {
      this.token = ''
      this.userInfo = null
      this.permissions = []
      this.roles = []
      this.menus = []
      Cookies.remove('token')
    },

    // 本地登出（不调用API，避免无限循环）
    localLogout() {
      this.clearUserData()
    },

    // 重置状态
    reset() {
      this.clearUserData()
    }
  }
})
